package com.kyxx.topics.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.bean.CommentBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.SettingUtils;
import com.kyxx.topics.utils.TimeUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.loopj.android.http.RequestParams;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.wang.avi.AVLoadingIndicatorView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cz.msebera.android.httpclient.Header;
import okhttp3.Call;
import okhttp3.Response;

public class MessageReplyActivity extends BaseActivity implements View.OnClickListener {
    private ImageView iv_avatar;
    private TextView tv_name;
    private TextView tv_content;
    private TextView tv_time;
    private TextView tv_jubao;
    private ImageView iv_like;
    private TextView tv_like;
    private TextView tv_write_value;
    private LinearLayout ll_like1;
    private ImageView iv_like1;
    private LinearLayout ll_share;
    private AlertDialog alertDialog;
    private EditText dialog_et_content;
    private TextView btn_submit;
    private TextView tv_remen;
    private ListView lv;
    private List<CommentBean> commentBeanList = new ArrayList<>();
    private View topView;
    private String pid;
    private int pageSize = 1;
    private int countSize = 10;
    ValueAdapter valueAdapter;
    private int lastVisiblePosition;
    private RelativeLayout rl_progress;
    private ProgressBar avi;
    private LinearLayout ll_reload;
    private int addComment;
    Intent intent = new Intent();
    private SettingUtils settingUtils = new SettingUtils();
    private CommentBean parentCommentBean = new CommentBean();
    protected DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisk(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .showImageOnFail(R.mipmap.icon_user_default)
            .showImageOnLoading(R.mipmap.icon_user_default)
            .showImageForEmptyUri(R.mipmap.icon_user_default)
            .build();
    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    rl_progress.setVisibility(View.GONE);
                    break;
                case 2:
                    switch (msg.arg1) {
                        case Constants.INITDATA:
                            rl_progress.setVisibility(View.VISIBLE);
                            avi.setVisibility(View.GONE);
                            ll_reload.setVisibility(View.VISIBLE);
                            break;
                        default:
                            rl_progress.setVisibility(View.GONE);
                            break;
                    }
                    break;
            }
        }
    };

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_reply);
    }

    @Override
    protected void loadTopBar(String title) {
        super.loadTopBar(title);
        top_bar_tv_left.setVisibility(View.GONE);
        top_bar_iv_left.setVisibility(View.VISIBLE);
        top_bar_tv_right.setVisibility(View.GONE);
        top_bar_iv_right.setVisibility(View.GONE);
        top_bar_iv_left.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_right));
        top_bar_iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        top_bar_iv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                popupWindow.showAsDropDown(top_bar_iv_right);
            }
        });
    }

    @Override
    protected void findViewById() {
        loadTopBar("评论");
        tv_write_value = (TextView) findViewById(R.id.tv_write_value);
        ll_like1 = (LinearLayout) findViewById(R.id.ll_like1);
        iv_like1 = (ImageView) findViewById(R.id.iv_like1);
        ll_share = (LinearLayout) findViewById(R.id.ll_share);
        lv = (ListView) findViewById(R.id.lv);
        rl_progress = (RelativeLayout) findViewById(R.id.rl_progress);
        avi = (ProgressBar) findViewById(R.id.avi);
        ll_reload = (LinearLayout) findViewById(R.id.ll_reload);
        ll_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getComment(Constants.INITDATA);
            }
        });
        initHeader();
    }

    @Override
    protected void setListener() {
        iv_avatar.setOnClickListener(this);
        tv_name.setOnClickListener(this);
        iv_like.setOnClickListener(this);
        tv_jubao.setOnClickListener(this);
        tv_write_value.setOnClickListener(this);
        ll_like1.setOnClickListener(this);
        ll_share.setOnClickListener(this);
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (lastVisiblePosition == lv.getLastVisiblePosition())
                    return;
                lastVisiblePosition = lv.getLastVisiblePosition();
                Log.e("topic", lastVisiblePosition + "onScroll" + lv.getCount());
                if (lastVisiblePosition == lv.getCount() - 2 && lv.getCount() >= countSize) {
                    pageSize++;
                    getComment(Constants.LOADMORE);
                }
            }
        });
    }

    @Override
    protected void processLogic() {
        pid = getIntent().getStringExtra("id");
        valueAdapter = new ValueAdapter();
        lv.setAdapter(valueAdapter);
        getComment(Constants.INITDATA);
    }

    private void initHeader() {
        topView = LayoutInflater.from(context).inflate(R.layout.layout_reply_header, null);
        iv_avatar = (ImageView) topView.findViewById(R.id.iv_avatar);
        tv_name = (TextView) topView.findViewById(R.id.tv_name);
        tv_content = (TextView) topView.findViewById(R.id.tv_content);
        tv_remen = (TextView) topView.findViewById(R.id.tv_remen);
        tv_time = (TextView) topView.findViewById(R.id.tv_time);
        tv_jubao = (TextView) topView.findViewById(R.id.tv_jubao);
        iv_like = (ImageView) topView.findViewById(R.id.iv_like);
        tv_like = (TextView) topView.findViewById(R.id.tv_like);
        switch (settingUtils.getZiTiDaXiao()) {
            case 0:
                tv_content.setTextSize(13);
                break;
            case 1:
                tv_content.setTextSize(17);
                break;
            case 2:
                tv_content.setTextSize(21);
                break;
        }
        lv.addHeaderView(topView);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_avatar:
                break;
            case R.id.tv_name:
                break;
            case R.id.iv_like:
                dianZanParent(parentCommentBean.getAid(), parentCommentBean.getId());
                break;
            case R.id.tv_jubao:
                break;
            case R.id.tv_write_value:
                showEditDialog(parentCommentBean.getAid(), parentCommentBean.getId());
                break;
            case R.id.ll_like1:
                dianZanParent(parentCommentBean.getAid(), parentCommentBean.getId());
                break;
            case R.id.ll_share:
                break;
        }
    }

    /**
     * 发送消息
     */
    private void showEditDialog(final String aid, final String pid) {
        if (alertDialog == null) {
            alertDialog = new AlertDialog.Builder(MessageReplyActivity.this, R.style.Translucent_NoTitle).create();
            View editView = getLayoutInflater().inflate(R.layout.ui_edit_comment, null);
            alertDialog.setView(editView);
            dialog_et_content = (EditText) editView.findViewById(R.id.send_commnet_ed_content);
            btn_submit = (TextView) editView.findViewById(R.id.btn_submit);
            alertDialog.show();
            Window win = alertDialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.FILL_PARENT; // 设置宽度
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setGravity(Gravity.BOTTOM);
            win.setAttributes(lp);
        } else {
            alertDialog.show();
        }
        dialog_et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(dialog_et_content.getText())) {
                    btn_submit.setEnabled(false);
                } else {
                    btn_submit.setEnabled(true);
                }
            }
        });
        final Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                InputMethodManager inputManager =
                        (InputMethodManager) dialog_et_content.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(dialog_et_content, 0);
                timer.cancel();
            }
        };
        timer.schedule(timerTask, 200);

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RequestParams params = new RequestParams();
                params.put("uid", BaseApp.getModel().getId());
                params.put("content", dialog_et_content.getText().toString());
                if (BaseApp.getModel().getAvatar() != null) {
                    params.put("avatar", BaseApp.getModel().getAvatar());
                } else {
                    params.put("avatar", "");
                }
                params.put("nickname", BaseApp.getModel().getNickname());
                params.put("aid", aid);
                params.put("pid", pid);
                params.put("parent_id", pid);
                params.put("receive_id", parentCommentBean.getUid());
                dialog_et_content.setText("");
                alertDialog.dismiss();
                RestClient.post(UrlUtils.COMMENT_ADD, params, context, new ResponseListener(MessageReplyActivity.this, true) {
                    @Override
                    public void success(int arg0, Header[] arg1, JSONObject result) {
                        try {
                            CommentBean commentBeanRefresh = (CommentBean) JSON.parseObject(result.getJSONObject("data").toString(), CommentBean.class);
                            commentBeanList.add(0, commentBeanRefresh);
                            valueAdapter.notifyDataSetChanged();
                            lv.setSelection(0);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ToastUtils.show(context, "评论成功");
                    }
                });
            }
        });
    }

    /**
     * 发送消息
     */
    private void showEditDialog(final CommentBean commentBean) {
        if (alertDialog == null) {
            alertDialog = new AlertDialog.Builder(MessageReplyActivity.this, R.style.Translucent_NoTitle).create();
            View editView = getLayoutInflater().inflate(R.layout.ui_edit_comment, null);
            alertDialog.setView(editView);
            dialog_et_content = (EditText) editView.findViewById(R.id.send_commnet_ed_content);
            btn_submit = (TextView) editView.findViewById(R.id.btn_submit);
            alertDialog.show();
            Window win = alertDialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.FILL_PARENT; // 设置宽度
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setGravity(Gravity.BOTTOM);
            win.setAttributes(lp);
        } else {
            alertDialog.show();
        }
        dialog_et_content.setHint("回复" + commentBean.getNickname() + ":");
        dialog_et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(dialog_et_content.getText())) {
                    btn_submit.setEnabled(false);
                } else {
                    btn_submit.setEnabled(true);
                }
            }
        });
        final Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                InputMethodManager inputManager =
                        (InputMethodManager) dialog_et_content.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(dialog_et_content, 0);
                timer.cancel();
            }
        };
        timer.schedule(timerTask, 200);

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RequestParams params = new RequestParams();
                params.put("uid", BaseApp.getModel().getId());
                params.put("content", dialog_et_content.getText().toString() + "\n@" + commentBean.getNickname() + ":" + commentBean.getContent());
                params.put("avatar", BaseApp.getModel().getAvatar());
                params.put("nickname", BaseApp.getModel().getNickname());
                params.put("aid", commentBean.getAid());
                params.put("pid", commentBean.getPid());
                params.put("parent_id", commentBean.getId());
                params.put("receive_id", commentBean.getUid());
                dialog_et_content.setText("");
                alertDialog.dismiss();
                RestClient.post(UrlUtils.COMMENT_ADD, params, context, new ResponseListener(MessageReplyActivity.this, true) {
                    @Override
                    public void success(int arg0, Header[] arg1, JSONObject result) {
                        try {
                            CommentBean commentBeanRefresh = (CommentBean) JSON.parseObject(result.getJSONObject("data").toString(), CommentBean.class);
                            commentBeanList.add(0, commentBeanRefresh);
                            valueAdapter.notifyDataSetChanged();
                            lv.setSelection(0);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        ToastUtils.show(context, "评论成功");
                    }
                });
            }
        });
    }

    private class ValueAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return commentBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return commentBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            final ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(context, R.layout.item_reply_value, null);
                holder.iv_avatar = (ImageView) view.findViewById(R.id.iv_avatar);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.tv_content = (TextView) view.findViewById(R.id.tv_content);
                holder.iv_like = (ImageView) view.findViewById(R.id.iv_like);
                holder.tv_like = (TextView) view.findViewById(R.id.tv_like);
                holder.tv_time = (TextView) view.findViewById(R.id.tv_time);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            switch (settingUtils.getZiTiDaXiao()) {
                case 0:
                    holder.tv_content.setTextSize(13);
                    break;
                case 1:
                    holder.tv_content.setTextSize(17);
                    break;
                case 2:
                    holder.tv_content.setTextSize(21);
                    break;
            }
            final CommentBean commentBean = commentBeanList.get(i);
            if (!TextUtils.isEmpty(commentBean.getAvatar())) {
                imageLoader.displayImage(commentBeanList.get(i).getAvatar(), holder.iv_avatar, options);
            } else {
                imageLoader.displayImage("", holder.iv_avatar, options);
            }
            if (TextUtils.isEmpty(commentBean.getNickname())) {
                holder.tv_name.setText("游客");
            } else {
                holder.tv_name.setText(commentBean.getNickname());
            }
            if (commentBean.getStatus() == 0) {
                holder.iv_like.setEnabled(true);
                holder.tv_like.setEnabled(true);
            } else {
                holder.iv_like.setEnabled(false);
                holder.tv_like.setEnabled(false);
            }
            holder.tv_like.setText(commentBean.getZan());
            holder.tv_content.setText(commentBean.getContent());
            holder.tv_time.setText(TimeUtils.milliseconds2String(Long.valueOf(commentBean.getAddtime()) * 1000, new SimpleDateFormat("MM-dd HH:mm")));
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showEditDialog(commentBean);
                }
            });
            holder.iv_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    RequestParams params = new RequestParams();
                    params.put("uid", BaseApp.getModel().getId());
                    params.put("avatar", BaseApp.getModel().getAvatar());
                    params.put("nicname", BaseApp.getModel().getNickname());
                    params.put("aid", commentBean.getAid());
                    params.put("cid", commentBean.getId());
                    RestClient.post(UrlUtils.DIANZAN, params, context, new ResponseListener(MessageReplyActivity.this, true) {
                        @Override
                        public void success(int arg0, Header[] arg1, JSONObject result) {
                            ToastUtils.show(context, "点赞成功");
                            commentBean.setZan(Integer.valueOf(holder.tv_like.getText().toString()) + 1 + "");
                            commentBean.setStatus(1);
                            notifyDataSetChanged();
                        }
                    });
                }
            });
            holder.tv_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    RequestParams params = new RequestParams();
                    params.put("uid", BaseApp.getModel().getId());
                    params.put("avatar", BaseApp.getModel().getAvatar());
                    params.put("nicname", BaseApp.getModel().getNickname());
                    params.put("aid", commentBean.getAid());
                    params.put("cid", commentBean.getId());
                    RestClient.post(UrlUtils.DIANZAN, params, context, new ResponseListener(MessageReplyActivity.this, true) {
                        @Override
                        public void success(int arg0, Header[] arg1, JSONObject result) {
                            ToastUtils.show(context, "点赞成功");
                            commentBean.setZan(Integer.valueOf(holder.tv_like.getText().toString()) + 1 + "");
                            commentBean.setStatus(1);
                            notifyDataSetChanged();
                        }
                    });
                }
            });
            return view;
        }
    }

    class ViewHolder {
        private ImageView iv_avatar;
        private TextView tv_name;
        private TextView tv_content;
        private ImageView iv_like;
        private TextView tv_like;
        private TextView tv_time;
    }

    private void getComment(final int type) {
        String url = UrlUtils.GETCHILD + "&uid=" + BaseApp.getModel().getId() + "&cid=" + pid + "&p=" + pageSize + "&rows=" + countSize;
        String cacheKey = "getchild&uid=" + BaseApp.getModel().getId() + "&cid=" + pid + "&p=" + pageSize + "&rows=" + countSize;
        OkGoRequest.get(url, MessageReplyActivity.this, cacheKey, CacheMode.REQUEST_FAILED_READ_CACHE, new StringCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                switch (type) {
                    case Constants.INITDATA:
                        rl_progress.setVisibility(View.VISIBLE);
                        avi.setVisibility(View.VISIBLE);
                        ll_reload.setVisibility(View.GONE);
                        break;
                    default:
                        rl_progress.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onCacheError(Call call, Exception e) {
                super.onCacheError(call, e);
                Message msg = new Message();
                msg.what = 2;
                msg.arg1 = type;
                handler.sendMessageDelayed(msg, Constants.DELAYTIMES);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                handler.sendEmptyMessageDelayed(0, Constants.DELAYTIMES);
                try {
                    JSONObject result = new JSONObject(s);
                    switch (type) {
                        case Constants.INITDATA:
                            JSONObject jsonObjectData = result.getJSONObject("data");
                            if (jsonObjectData.getString("avatar") != null)
                                imageLoader.displayImage(jsonObjectData.getString("avatar"), iv_avatar, options);
                            if (jsonObjectData.getString("nickname") != null)
                                tv_name.setText(jsonObjectData.getString("nickname"));
                            tv_like.setText(jsonObjectData.getString("zan"));
                            tv_content.setText(jsonObjectData.getString("content"));
                            if (jsonObjectData.getInt("status") == 0) {
                                iv_like1.setEnabled(true);
                                iv_like.setEnabled(true);
                                ll_like1.setEnabled(true);
                            } else {
                                iv_like1.setEnabled(false);
                                iv_like.setEnabled(false);
                                ll_like1.setEnabled(false);
                            }
                            tv_time.setText(TimeUtils.milliseconds2String(Long.valueOf(jsonObjectData.getString("addtime")) * 1000, new SimpleDateFormat("MM-dd HH:mm")));
                            commentBeanList = JSON.parseArray(result.getJSONObject("data").getJSONArray("children").toString(), CommentBean.class);
                            if (commentBeanList != null) {
                                tv_remen.setVisibility(View.VISIBLE);
                            } else {
                                tv_remen.setVisibility(View.GONE);
                            }
                            break;
                        case Constants.LOADMORE:
                            commentBeanList.addAll(JSON.parseArray(result.getJSONObject("data").getJSONArray("children").toString(), CommentBean.class));
                            break;
                    }
                    if (commentBeanList != null)
                        valueAdapter.notifyDataSetChanged();
                    lastVisiblePosition = lv.getLastVisiblePosition();
                } catch (JSONException e) {
                    e.printStackTrace();
                    tv_remen.setVisibility(View.GONE);
                }
            }
        });
    }

    private void dianZanParent(String aid, String cid) {
        RequestParams params = new RequestParams();
        params.put("uid", BaseApp.getModel().getId());
        params.put("avatar", BaseApp.getModel().getAvatar());
        params.put("nicname", BaseApp.getModel().getNickname());
        params.put("aid", aid);
        params.put("cid", cid);
        RestClient.post(UrlUtils.DIANZAN, params, context, new ResponseListener(MessageReplyActivity.this, true) {
            @Override
            public void success(int arg0, Header[] arg1, JSONObject result) {
                ToastUtils.show(context, "点赞成功");
                tv_like.setText(Integer.valueOf(tv_like.getText().toString()) + 1 + "");
                iv_like1.setEnabled(false);
                iv_like.setEnabled(false);
                ll_like1.setEnabled(false);
                parentCommentBean.setZan(Integer.valueOf(parentCommentBean.getZan()) + 1 + "");
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", parentCommentBean);
                intent.putExtra("add_child_count", addComment);
                intent.putExtras(bundle);
                setResult(47, intent);
            }
        });
    }
}
